package api.ws.server.msg;

import basic.common.context.SpringContext;
import basic.common.result.SystemException;
import basic.common.ws.Message;
import basic.common.ws.WsContext;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @创建人 xiaojiancheng
 * @时间 2021/1/5
 * @描述 $
 */
@Component
public class MessageExecutorContainer {
    private Map<String,IMessageExecutor> executorMap = new HashMap<>();

    {
        SpringContext.register(context -> {
            Map<String, IMessageExecutor> beansOfType = context.getBeansOfType(IMessageExecutor.class);
            beansOfType.forEach((k,v) -> {
                executorMap.put(v.type(),v);
            });
        });
    }

    public Mono<Message> execute(WsContext context){
        Message msg = context.getMessage();
        IMessageExecutor executor = executorMap.get(msg.getType());

        if(executor == null){
            return Mono.error(new SystemException(-1,"不支持的type, type = "+msg.getType()));
        }

        return executor.execute(context);
    }
}
